package com.example.yang.yixin.Activity;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.yang.yixin.R;
import com.example.yang.yixin.Views.InputView;

/**
 * @address BeiJing
 * @author LiXufei
 * @function  拍照取图相册取图
 */
public class FaceActivity extends BaseActivity{

    private ImageView imageView;
    private int TAKE_PHOTO=1;   //拍照
    private int GET_PHOTO=2;
    SharedPreferences pref;
    SharedPreferences.Editor editor;//取照片
    private Button camera;
    private Button club;
    private ImageView mIv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face);
        //获取ImageView控件
        imageView = (ImageView) findViewById(R.id.takePhoto_imageView);
        pref=getSharedPreferences("user",MODE_PRIVATE);
        editor=pref.edit();
        camera=(Button)findViewById(R.id.takePhoto_bt1);
        club=(Button)findViewById(R.id.takePhoto_bt2);
        mIv_back=findViewById(R.id.iv_back);
        mIv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(FaceActivity.this,MeActivity.class);
                startActivity(intent);
            }
        });
        showdialog();
        Init();


        /*
         * 拍照取图
         */
        camera.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                //设置拍照意图
                Intent mIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(mIntent, TAKE_PHOTO);

            }
        });

        /*
         * 相册取图
         */
        club.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, GET_PHOTO);

            }
        });

    }

    private void showdialog() {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setIcon(R.mipmap.logo1)
                    .setTitle(R.string.app_name)
                    .setMessage("您仅可以修改三次个人照片哦，请在必要时修改！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.show();

    }

    private void Init() {
        initNarvBar(true,"人脸设置",false);
    }

    //接受回传值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {  //回传值接受成功

            if (requestCode == TAKE_PHOTO) {    //拍照取图

                Bundle bundle = data.getExtras();
                //获取data数据集合
                Bitmap bitmap = (Bitmap) bundle.get("data");//获得data数据
                int changetime=pref.getInt("changetime",100);
                if(changetime==100){
                 editor.putInt("changetime",3);
                 editor.apply();//设置仅可以三次修改图片
               }
               if(pref.getInt("changetime",100)>0) {
                   saveBitmapToSDCard(bitmap, "rootpic");
                   int temp=pref.getInt("changetime",100);
                   editor.putBoolean("INPUT_OR_NOT",true);
                   editor.putInt("changetime",temp-1);
                   editor.apply();
                   Snackbar.make(getWindow().getDecorView(),"照片已保存哦",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {

                       }
                   }).show();
               }
               else{
                   Toast.makeText(getApplicationContext(),"您的修改次数已达上限！",Toast.LENGTH_LONG).show();
               }
                Log.i("TAG", "拍照回传bitmap："+bitmap);

            }

            if (requestCode == GET_PHOTO) {     //相册取图

                ContentResolver contentResolver = getContentResolver();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(data.getData()));
                    Log.i("TAG", "从相册回传bitmap："+bitmap);
                    saveBitmapToSDCard(bitmap, "rootpic");
                    int temp=pref.getInt("changetime",100);
                    editor.putBoolean("INPUT_OR_NOT",true);
                    editor.putInt("changetime",temp-1);
                    editor.apply();
                    Snackbar.make(getWindow().getDecorView(),"照片已保存哦",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }

        }

    }

    public void saveBitmapToSDCard(Bitmap bitmap, String imagename)
    {
        FileOutputStream fos = null;
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
        try {
            fos = new FileOutputStream("/sdcard/Pictures/" +imagename+ ".jpg");
            if (fos != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
